package com.kaikeba.controller;

import com.kaikeba.bean.Message;
import com.kaikeba.dao.impl.AdminDaoMysql;
import com.kaikeba.mvc.ResponseBody;
import com.kaikeba.service.AdminService;
import com.kaikeba.util.JSONUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class AdminController {

    @ResponseBody("/admin/login.do")
    public String login(HttpServletRequest request, HttpServletResponse response){

        //设置编码

        //         1、接收数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //        2、调用service获取结果
        Boolean loginResult = AdminService.login(username, password);
        //       3、根据结果，返回不同的数据
        Message message = null;
        if(loginResult){
            message = new Message(0,"登录成功");
            // 登录时间和IP的更新
            Date date = new Date();
            String remoteAddr = request.getRemoteAddr();
            AdminService.updateTimeAndIp(username,date,remoteAddr);
            request.getSession().setAttribute("adminUserName",username);

        }else{
            message = new Message(-1,"登录失败");
        }
        //        4、将数据转化成JSON
        //由于Message是一个对象，无法直接返回，所以使用JSON转化
        String JSON = JSONUtil.toJSON(message);
        return JSON;

    }
}
